<?php
function check_verify($code){	
	$verify = new \Think\Verify();
	return $verify->check($code);
}

function createNoncestr( $length = 32 ) 
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
		$str ="";
		for ( $i = 0; $i < $length; $i++ )  {  
			$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
		}  
		return $str;
	}
	
function access_token(){		//获取access_token
	if(!S('access_token')){
		$appid = C('appid');
		$appsectrt = C('appsecret');
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsectrt;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($output,true);
		//dump($arr);
		S('access_token',$arr['access_token'],7000);
	}
	//dump(S('access_token'));
	return S('access_token');
    //return $arr["access_token"];
}
function jsapi_ticket(){
	if(!S('jsapi_ticket')){
		$appid = C('appid');
		$appsectrt = C('appsecret');
		$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".access_token()."&type=jsapi";
		//echo $url;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		$output = curl_exec($ch);
		curl_close($ch);
		$arr = json_decode($output,true);
		//dump($arr);
		//$arr2['time'] = time();
		//$arr2['key'] = $arr['ticket'];
		S('jsapi_ticket',$arr['ticket'],7000);
	}
	//dump(S('jsapi_ticket'));
	return S('jsapi_ticket');
}
/**
	 * 	作用：格式化参数，签名过程需要使用
	 */
	function formatBizQueryParaMap($paraMap, $urlencode)
	{
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v)
		{
		    if($urlencode)
		    {
			   $v = urlencode($v);
			}
			//$buff .= strtolower($k) . "=" . $v . "&";
			$buff .= $k . "=" . $v . "&";
		}
		if (strlen($buff) > 0) 
		{
			$reqPar = substr($buff, 0, strlen($buff)-1);
		}
		return $reqPar;
	}
	
function signature(){
	$Obj['jsapi_ticket'] = jsapi_ticket();
	$Obj['noncestr'] = createNoncestr();
	$Obj['url'] = str_replace("/index.php?s=","","http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
	$Obj['timestamp'] = time();
	
	foreach ($Obj as $k => $v){
		$Parameters[$k] = $v;
	}
	//签名步骤一：按字典序排序参数
	ksort($Parameters);
	$String = formatBizQueryParaMap($Parameters, false);
	//echo '【string1】'.$String.'</br>';
	//签名步骤二：在string后加入KEY
	//$String = $String."&key=".C('mch_key');
	//echo "【string2】".$String."</br>";
	//签名步骤三：MD5加密
	$String = sha1($String);
	//echo "【string3】 ".$String."</br>";
	//签名步骤四：所有字符转为大写
	//$Obj['signature'] = strtoupper($String);
	$Obj['signature'] = $String;
	
        
	return $Obj;
}

function curl($url,$post=NULL){
	
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	if(stripos($url,"https://")!==FALSE){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
			curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	if(isset($post)){	// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}
	
	$output = curl_exec($ch);
	curl_close($ch);
	
	return $output;
	
}

/**
* 微信api不支持中文转义的json结构
* @param array $arr
*/
	
function json_encode2($arr) {
		$parts = array ();
		$is_list = false;
		//Find out if the given array is a numerical array
		$keys = array_keys ( $arr );
		$max_length = count ( $arr ) - 1;
		if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
			$is_list = true;
			for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
				if ($i != $keys [$i]) { //A key fails at position check.
					$is_list = false; //It is an associative array.
					break;
				}
			}
		}
		foreach ( $arr as $key => $value ) {
			if (is_array ( $value )) { //Custom handling for arrays
				if ($is_list)
					$parts [] = json_encode2 ( $value ); /* :RECURSION: */
				else
					$parts [] = '"' . $key . '":' . json_encode2( $value ); /* :RECURSION: */
			} else {
				$str = '';
				if (! $is_list)
					$str = '"' . $key . '":';
				//Custom handling for multiple data types
				if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
					$str .= $value; //Numbers
				elseif ($value === false)
				$str .= 'false'; //The booleans
				elseif ($value === true)
				$str .= 'true';
				else
					$str .= '"' . addslashes ( $value ) . '"'; //All other things
				// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
				$parts [] = $str;
			}
		}
		$json = implode ( ',', $parts );
		if ($is_list)
			return '[' . $json . ']'; //Return numerical JSON
		return '{' . $json . '}'; //Return associative JSON
}
	
function newmms($tel, $content){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "http://115.238.169.140:8888/sms.aspx?action=send&userid=207&account=%E7%83%9F%E5%8F%B0%E4%BF%A1%E5%8D%9A&password=a222222&mobile=".$tel."&content=".$content."【佛山医院】&sendTime=&extno=");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

	$res = curl_exec( $ch );
	curl_close( $ch );
	//$res  = curl_error( $ch );
	return $res;
}


//function mms($key,$tel,$content){
//	$ch = curl_init();
//	curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send.json");
//
//	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
//	curl_setopt($ch, CURLOPT_HEADER, FALSE);
//
//	curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);
//	curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-'.$key);
//
//	curl_setopt($ch, CURLOPT_POST, TRUE);
//	curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile' => $tel,'message' => $content.'【纺织屋】'));
//
//	$res = curl_exec( $ch );
//	curl_close( $ch );
//	//$res  = curl_error( $ch );
//	//var_dump($res);
//	return $res;
//}
function chat_Token()
{
	if(checkCookie()==1)
	{
		if(!$_SESSION['token'])
		{
			$uid = cookie('uid');
			//	$uid = 1052;
			$user=D('User');
			$map['uid']=$uid;
			$sql=$user->where($map)->find();
			import("@.Util.IMAPI");
			$im = new \IMAPI("sfci50a7ch8oi", "hrXGsSGDzlTi");
			$imgurl=$sql['headimgurl'];
			if(!$imgurl)
				$imgurl='http://'.$_SERVER['SERVER_NAME'].'/Uploads/system/pic01.jpg';
			$res=$im->getToken($uid, $uid, $imgurl);
			$arrRes=json_decode($res,true);
			$_SESSION['token']=$arrRes['token'];
		}
		return $_SESSION['token'];
	}
	else return "";
}
function get_url() 
{
	$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
	$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
	$path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
	$relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
	return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
function is_weixin()
{
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) 
	{
		return true;
	}
	return false;
}

function createRandomCode($cls)
{
	import("@.Util.IdentifyCode");
	$generate = new \IdentifyCode();
	$code="";
	switch ($cls)
	{
		case 'A' : 
			$code=$generate->createLowcharCode(6);
			break;
		case 'B' : 
			$code=$generate->createRandCode(8);
			break;
		case 'I' :
			$code=$generate->createNumberCode(6);
			break;
		default: $code=$generate->createRandCode(8);break;
	}
	return $code;
}


function resetmenu() {

        $menuList = M('wechatMenu')->order('sort desc')->limit('3')->select();

        $post = array();

        $post['button'] = array();

        for($i=0; $i<count($menuList); $i++) {

                $post['button'][$i] = array();

                $menu = $menuList[$i];

                $itemList = M('wechatMenuItem')->where('menu_id='.$menu['menu_id'])->order('sort desc')->select();

                $post['button'][$i]['name'] = $menu['menu_name'];

                if(count($itemList) == 0) {

                        $post['button'][$i]['type'] = 'view';

                        $post['button'][$i]['url'] = $menu['target_url'];

                } else {

                        $subArray = array();

                        for($j=0; $j<count($itemList); $j++) {

                                $item = $itemList[$j];

                                $subArray[$j] = array();

                                $subArray[$j]['type'] = 'view';
                                $subArray[$j]['name'] = $item['name'];
                                $subArray[$j]['url'] = $item['target_url'];

                        }

                        $post['button'][$i]['sub_button'] = $subArray;

                }

        }

        return json_encode2($post);

}

function checkCookie()
{
	$uid=I('cookie.uid');
	if(!empty($uid))
	{
		return "1";
	}
	else
	{
		return "0";
	}
}

/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content, $attachment="") {

    Vendor('PHPMailer.PHPMailerAutoload');     
    $mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
    $mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
    $mail->Username = C('MAIL_USERNAME'); //你的邮箱名
    $mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
    $mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
    $mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
    $mail->AddAddress($to,"尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
    $mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
    $mail->Subject =$title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示

    //添加附件
    if(!isNullOrEmpty($attachment)) {
        foreach ($attachment as $item) {
            $mail->addAttachment($item['path'], $item['name']);
        }
    }
    
    return($mail->Send());
}

function GetRandStr($len) 
{ 
    $chars = array( 
//        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
//        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
//        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
//        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
//        "S", "T", "U", "V", "W", "X", "Y", "Z", 
        "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
    ); 
    $charsLen = count($chars) - 1; 
    shuffle($chars);   
    $output = ""; 
    for ($i=0; $i<$len; $i++) 
    { 
        $output .= $chars[mt_rand(0, $charsLen)]; 
    }  
    return $output;  
} 

function GetRandAllStr($len) 
{ 
    $chars = array( 
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",  
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",  
        "S", "T", "U", "V", "W", "X", "Y", "Z", 
        "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
    ); 
    $charsLen = count($chars) - 1; 
    shuffle($chars);   
    $output = ""; 
    for ($i=0; $i<$len; $i++) 
    { 
        $output .= $chars[mt_rand(0, $charsLen)]; 
    }  
    return $output;  
}


function getModelValidName($str) {
	$array = explode('\\',$str);
	$length = count($array);
	$lastStr = $array[$length-1];
	$validStr = strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $lastStr));
	$validStr = str_replace("_model", "", strtolower($validStr));
	return $validStr;
}

function mapTablePrefixName($tableName) {

	$prefix = $tableName;

	$array = array("product_desc"=>"desc",
                    "booking_log"=>"log",
                    "activity_join"=>"join");

	if(array_key_exists($tableName, $array)) {
		$prefix = $array[$tableName];
	}

	return $prefix . "_id";

}

function getWhereSqlByMap($map) {

	$returnStr = "1=1";

	foreach($map as $key=>$value) {

		$keyArray = explode("-", $key);

		$flag = "eq";

		if(!isNullOrEmpty($keyArray[1])) {
			$flag = $keyArray[1];
		}

		$columnName = str_replace("#", ".", $keyArray[0]);

		switch($flag) {
			case "eq":
				$returnStr .= " and " . $columnName . " = '" . $value . "'";
				break;
			case "leftLike":
				$returnStr .= " and " . $columnName . " like '%" . $value . "'";
				break;
			case "rightLike":
				$returnStr .= " and " . $columnName . " like '" . $value . "%'";
				break;
			case "like":
				$returnStr .= " and " . $columnName . " like '%" . $value . "%'";
				break;
			case "lt":
				$returnStr .= " and " . $columnName . " < '" . $value . "'";
				break;
			case "elt":
				$returnStr .= " and " . $columnName . " <= '" . $value . "'";
				break;
			case "gt":
				$returnStr .= " and " . $columnName . " > '" . $value . "'";
				break;
			case "egt":
				$returnStr .= " and " . $columnName . " >= '" . $value . "'";
				break;
			case "in":
				$returnStr .= " and " . $columnName . " in (" . $value . ")";
				break;
			default:
				break;
		}

	}
	return $returnStr;
}

function geoGetDistance($lat1, $lng1, $lat2, $lng2) {
	//地球半径
	$R = 6378137;
	//将角度转为狐度
	$radLat1 = deg2rad($lat1);
	$radLat2 = deg2rad($lat2);
	$radLng1 = deg2rad($lng1);
	$radLng2 = deg2rad($lng2);
	//结果
	$s = acos(cos($radLat1)*cos($radLat2)*cos($radLng1-$radLng2)+sin($radLat1)*sin($radLat2))*$R;
	//精度
	$s = round($s* 10000)/10000;
	return  round($s);
}

function httpRequest($url, $data=array()){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // 我们在POST数据哦！
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
function getTemplateById($templateId, $list) {

    $template = null;

    foreach ($list as $item) {
        if($item["template_id"] == $templateId) {
            $template = $item;
            break;
        }
    }

    return $template;
}

function getTemplateList() {
    //获得access_token
    $accessToken=access_token();

    $result = httpRequest("https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=$accessToken");

    $resultArray = json_decode($result, true);

    $list = $resultArray["template_list"];

    foreach ($list as &$item) {
        $content = str_replace(":", "：", $item["content"]);
        preg_match_all("/{{(.*?)\./",$content,$keys);
        $item["keys"] = $keys[1];
        array_splice($item["keys"],0,1);
        array_splice($item["keys"],count($item["keys"])-1,1);
        preg_match_all("/(.*?)：/",$content,$values);
        $item["values"] = $values[1];
    }

    return $list;

}

function getRuleSelectOptionHtml($ruleId = 0, $hasAll = 0) {
    $shopList = D('Rule')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($shopList as $c) {

        $selected = '';

        if ($c['rule_id'] == $ruleId)
            $selected = 'selected="selected"';

        $html .= '<option days="'.$c["days"].'" value="' . $c['rule_id'] . '" ' . $selected . ' >' . $c['desc'] . '</option>';
    }
    return $html;
}

function getShopSelectOptionHtml($shopId = 0, $hasAll = 0) {
    $shopList = D('Shop')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($shopList as $c) {

        $selected = '';

        if ($c['shop_id'] == $shopId)
            $selected = 'selected="selected"';

        $html .= '<option contact="'.$c["contact"].'" address="'.$c["address"].'" value="' . $c['shop_id'] . '" ' . $selected . ' >' . $c['shop_name'] . '</option>';
    }
    return $html;
}

function getAddressSelectOptionHtml($addressId = 0, $hasAll = 0) {
    $shopList = D('Address')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($shopList as $c) {

        $selected = '';

        if ($c['address_id'] == $addressId)
            $selected = 'selected="selected"';

        $html .= '<option address="'.$c["address"].'" value="' . $c['address_id'] . '" ' . $selected . ' >' . $c['name'] . '</option>';
    }
    return $html;
}

function getCategorySelectOptionHtml($categoryId = 0, $hasAll = 0) {
    $categoryList = D('Category')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($categoryList as $c) {

        $selected = '';

        if ($c['category_id'] == $categoryId)
            $selected = 'selected="selected"';

        $html .= '<option needDoctor="'.$c["need_doctor"].'" value="' . $c['category_id'] . '" ' . $selected . ' >' . $c['category_name'] . '</option>';
    }
    return $html;
}

function getClassSelectOptionHtml($classId = 0, $hasAll = 0) {
    $classList = D('Class')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($classList as $c) {

        $selected = '';

        if ($c['class_id'] == $classId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['class_id'] . '" ' . $selected . ' >' . $c['class_name'] . '</option>';
    }
    return $html;
}

function getFaqClassSelectOptionHtml($classId = 0, $hasAll = 0) {
    $classList = D('FaqClass')
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($classList as $c) {

        $selected = '';

        if ($c['faq_class_id'] == $classId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['faq_class_id'] . '" ' . $selected . ' >' . $c['faq_class_name'] . '</option>';
    }
    return $html;
}

function getRxSelectOptionHtml($rxId, $patientName) {
    $List = D('Rx')->alias('r')
        ->join("left join __ADMIN__ a on a.user_id = r.update_id")
        ->where(array('patient_name' => $patientName))
        ->order("r.rx_id desc")
        ->field("r.*, a.admin_name")
        ->select();
    $html = '<option value="-1"></option>';

    foreach ($List as $c) {
        if($c["rx_id"] == $rxId)
            continue;
        $selected = '';
        $html .= '<option value="' . $c["rx_id"] . '" ' . $selected . ' >' . $c["patient_name"] . '_' . $c["side"] .'_'. $c["admin_name"] .'于（' . $c["update_time"] . '）更新</option>';
    }
    return $html;
}

function getFormDictSelectOptionHtml($id,$index, $className, $hasAll = 0) {
    $map["index"] = array('like',$index.'_%');
    $map["class_name"] = $className;
    $List = D('FormDict')
        ->where($map)
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0"></option>';

    foreach ($List as $c) {

        $selected = '';

        if (substr($c['index'],strlen($index),strlen($c['index'])) == "_".$id)
            $selected = 'selected="selected"';

        $html .= '<option value="' . substr($c['index'],strlen($index)+1,strlen($c['index'])) . '" ' . $selected . ' >' . $c['name'] . '</option>';
    }
    return $html;
}

function getFormDictArr($index, $className) {
    $map["index"] = array('like',$index.'_%');
    $map["class_name"] = $className;
    $List = D('FormDict')
        ->where($map)
        ->select();
    return $List;
}

function getFormDictSelectOption($value,$index, $className, $hasAll = 0) {
    $map["index"] = array('like',$index.'_%');
    $map["class_name"] = $className;
    $List = D('FormDict')
        ->where($map)
        ->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value=""></option>';

    foreach ($List as $c) {

        $selected = '';

        if ($c['name'] == $value)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['name'] . '" ' . $selected . ' >' . $c['name'] . '</option>';
    }
    return $html;
}

function getProductSelectOptionHtml($productId = 0, $hasAll = 0) {
    $productList = D('Product')
        ->select();

    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($productList as $c) {

        $selected = '';

        if ($c['product_id'] == $productId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['product_id'] . '" ' . $selected . ' >' . $c['product_name'] . '</option>';
    }
    return $html;
}

function getEmployeeSelectOptionHtml($job, $jobDetail, $hasNone) {
    $List = D('Employee')
        ->select();
    $html = '';
    if ($hasNone == 1)
        $html .= '<option value="-1">无</option>';
    if ($hasNone == 2)
        $html .= '<option value="-1">下单人</option>';
    foreach ($List as $c) {

        $selected = '';
        $jobArr = explode(',',$c["job"]);
        if($jobDetail == 0){// 全部
            $html .= '<option value="' . $c["employee_id"] . '" ' . $selected . ' >' . $c["employee_name"] . '</option>';
        }else if ($jobArr[$job] == $jobDetail){
            $html .= '<option value="' . $c["employee_id"] . '" ' . $selected . ' >' . $c["employee_name"] . '</option>';
        }
    }
    return $html;
}

function getChartSelectOptionHtml() {
    $map["point"] = array("gt", 0);
    $List = D('Customer')
        ->where($map)
        ->select();
    $html = '';

    foreach ($List as $c) {

        $selected = '';
        $html .= '<option value="' . $c['customer_id'] . '" ' . $selected . ' >' . $c['nickname'] .'('.$c['customer_id'].')'. '</option>';

    }
    return $html;
}

function getAgentSelectOptionHtml($finishedProductId, $agentId) {
//    $html = '';
//    $html .= '<option value="0"></option>';
//
//    for($i=0;$i<count($agentNameArr);$i++) {
//        $selected = '';
//        $html .= '<option value="' . $agentPriceArr[$i] . '" ' . $selected . ' >' . $agentNameArr[$i] . '</option>';
//    }
    $map["finished_product_id"] = $finishedProductId;

    $agentList = D('Agent')
        ->where($map)
        ->select();
    $html = '';
    $html .= '<option value="0"></option>';

    if(isNullOrEmpty($agentId)){//非代理
        foreach ($agentList as $c) {
            $selected = '';
            $value = $c['agent_price'] . "," . $c['agent_contact'] . "," . $c['agent_tel'] . "," . $c['agent_address'] . "," . $c['agent_invoice_name'] . "," . $c['agent_invoice_number'] . "," . $c['need_patient'] . "," . $c['fixed_price'];
            $html .= '<option value="' . $value . '" ' . $selected . ' >' . $c['agent_name'] . '</option>';
        }
    }else{//代理
        $agentIdArr = explode(",", $agentId);
        foreach ($agentList as $c) {
            if(in_array($c['agent_id'], $agentIdArr)){
                $selected = '';
                $value = $c['agent_price'] . "," . $c['agent_contact'] . "," . $c['agent_tel'] . "," . $c['agent_address'] . "," . $c['agent_invoice_name'] . "," . $c['agent_invoice_number'] . "," . $c['need_patient'] . "," . $c['fixed_price'];
                $html .= '<option value="' . $value . '" ' . $selected . ' >' . $c['agent_name'] . '</option>';
            }
        }
    }

    return $html;
}

function getCompanySelectOptionHtml($companyId = 0, $hasAll = 0) {
    $CompanyList = D('Company')
        ->select();

    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($CompanyList as $c) {

        $selected = '';

        if ($c['company_id'] == $companyId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['company_id'] . '" ' . $selected . ' >' . $c['company_name'] . '</option>';
    }
    return $html;
}

function getCitySelectOptionHtml($cityId = 0, $hasAll = 0) {
    $cityList = D('City')->select();
    $html = '';
    if ($hasAll == 1)
        $html .= '<option value="0">全部</option>';

    foreach ($cityList as $c) {

        $selected = '';

        if ($c['city_id'] == $cityId)
            $selected = 'selected="selected"';

        $html .= '<option value="' . $c['city_id'] . '" ' . $selected . ' >' . $c['city_name'] . '</option>';
    }
    return $html;
}

/**
 * 订单成功提醒
 * @param $data
 * @return bool
 */
function orderSuccessNotify($data) {

    //获得access_token
    $accessToken=access_token();

//    $openidArray = array("otBeowu8bYi2HBRTMBWSIWzzkkbo","otBeowlAfkwtcoHunTHTDVQucZ_E","otBeowv0VZQORekZps57qRBc5d_0","otBeowqZt1N7mSXkLOk4y0ejgVvY","otBeowhbac8rUznUs_ijq2gBKdUM","otBeowka3Gu-RmDy_Fo5rlFCRdrs");

    $employeeList = D("Employee")->alias("e")
        ->join("left join __CUSTOMER__ c on c.customer_id = e.employee_id")
        ->field("e.*, c.openid")
        ->select();
    $openidArray = array();
    foreach ($employeeList as $singleEmployee) {
        $job = explode(',', $singleEmployee["job"]);
        if ($job[0] == "5" || $job[0] == "3" || $job[0] == "100") {//西钓客服
            array_push($openidArray, $singleEmployee["openid"]);
        }
    }

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"D5UvITf8REy9mUag2TVtei1Y2no4gzLMSkLC8vksVZc",
            'data'=>array(
                'first'=>array(
                    'value'=>$data["title"]),
                'keyword1'=>array(
                    'value'=>$data["orderNumber"]),
                'keyword2'=>array(
                    'value'=>$data["price"]),
                'keyword3'=>array(
                    'value'=>getCurrentDate()),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 付款成功提醒
 * @param $data
 * @return bool
 */
function paymentSuccessNotify($data) {

    //获得access_token
    $accessToken=access_token();

//    $openidArray = array("otBeowu8bYi2HBRTMBWSIWzzkkbo","otBeowlAfkwtcoHunTHTDVQucZ_E","otBeowv0VZQORekZps57qRBc5d_0","otBeowqZt1N7mSXkLOk4y0ejgVvY","otBeowhbac8rUznUs_ijq2gBKdUM","otBeowka3Gu-RmDy_Fo5rlFCRdrs");

    $employeeList = D("Employee")->alias("e")
        ->join("left join __CUSTOMER__ c on c.customer_id = e.employee_id")
        ->field("e.*, c.openid")
        ->select();
    $openidArray = array();
    foreach ($employeeList as $singleEmployee) {
        $job = explode(',', $singleEmployee["job"]);
        if ($job[2] == "2" || $job[0] == "2" || $job[0] == "100") {//财务和销售
            array_push($openidArray, $singleEmployee["openid"]);
        }
//        if ($job[0] == "101") {
//            array_push($openidArray, $singleEmployee["openid"]);
//        }
    }

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"D5UvITf8REy9mUag2TVtei1Y2no4gzLMSkLC8vksVZc",
            'data'=>array(
                'first'=>array(
                    'value'=>$data["title"]),
                'keyword1'=>array(
                    'value'=>$data["orderNumber"]),
                'keyword2'=>array(
                    'value'=>$data["price"]),
                'keyword3'=>array(
                    'value'=>getCurrentDate()),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 订单发货提醒
 * @param $data
 * @return bool
 */
function orderEndNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"t1o4chfifbWfLi7upyi8yLyVROe60FY5qbqtKtg2H2M",
            'url'=>"http://xwkang.com/wechat/userCenter/myOrder",
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 成品下单通知
 * @param $data
 * @return bool
 */
function finishedOrderNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"eSeOrcPNK1l4lZWLZVhHJGp2-snkeWL-SXCr4yFMW0w",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'keyword4'=>array(
                    'value'=>$data["keyword4"]),
                'keyword5'=>array(
                    'value'=>$data["keyword5"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 成品订单发货提醒
 * @param $data
 * @return bool
 */
function finishedOrderEndNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"gyHNdWiTDp4vf2z0yAmNMbH7nAk9p5Io0IxU34txL_0",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 工单提交提醒
 * @param $data
 * @return bool
 */
function WorkorderCreateNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"JnSfpkqgV0yC3-jerXCpsDIaXpQIFxB9oN8pRlRvCPg",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}
/**
 * 工单提交提醒
 * @param $data
 * @return bool
 */
function WorkorderChangeNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"7zzT1XcYa0_KlovbUkUG2x-Cq5mgb-sYWBo8JciZO-k",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}
/**
 * 工单接单提醒
 * @param $data
 * @return bool
 */
function WorkorderProcessingNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"XTdJtzjQmhIf04XjyqP6Vr8hnSoT1J43aj18ZBwulcU",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}
/**
 * 工单完成提醒
 * @param $data
 * @return bool
 */
function workorderEndNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"UYGNEYl8wLWnOi73t1Ic7Y9ffk7arok12gxgAGoDTOQ",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'keyword4'=>array(
                    'value'=>$data["keyword4"]),
                'keyword5'=>array(
                    'value'=>$data["keyword5"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 免费评估通知
 * @param $data
 * @return bool
 */
function evaluateNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);

    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"kz4tRfc8mDbzjzyP02v9JUlfJlQil4QtB0B_osRlPmU",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

function calculateDRAFO($perimeter, $size, $sex) {

    if($sex == "1") {

        if($perimeter > 266
            && $perimeter < 292
            && $size >= 38.5 && $size <= 40.5) {
            return "尺寸2";
        } elseif($perimeter > 292
            && $perimeter < 317
            && $size >= 40.5 && $size <= 43) {
            return "尺寸3";
        } elseif($perimeter > 317
            && $perimeter < 343
            && $size >= 42.5 && $size <= 45) {
            return "尺寸4";
        } elseif($perimeter > 343
            && $perimeter < 368
            && $size >= 45 && $size <= 47.5) {
            return "尺寸5";
        } else {
            return "无法定位";
        }

    } elseif($sex == "0") {

        if($perimeter > 266
            && $perimeter < 292
            && $size >= 38.5 && $size <= 40.5) {
            return "尺寸2";
        } elseif($perimeter > 292
            && $perimeter < 317
            && $size >= 40.5 && $size <= 43) {
            return "尺寸3";
        } elseif($perimeter > 317
            && $perimeter < 343
            && $size >= 42.5 && $size <= 43) {
            return "尺寸4";
        } else {
            return "无法定位";
        }

    } else {
        return "无法定位";
    }

}

function calculateIowaData($footLength) {

    if(($footLength > 0 && $footLength < 88)) {
        return "矫正鞋号000，连杆尺寸8英寸(20.32厘米)";
    } elseif (($footLength >= 88 && $footLength < 92)) {
        return "矫正鞋号00，连杆尺寸8英寸(20.32厘米)";
    } elseif (($footLength >= 92 && $footLength < 97)) {
        return "矫正鞋号0，连杆尺寸8英寸(20.32厘米)";
    } elseif(($footLength >= 97 && $footLength < 102)) {
        return "矫正鞋号1，连杆尺寸8英寸(20.32厘米)";
    } elseif (($footLength >= 102 && $footLength < 112.1)) {
        return "矫正鞋号2，连杆尺寸8英寸(20.32厘米)";
    } elseif (($footLength >= 112.1 && $footLength < 122.2)) {
        return "矫正鞋号3，连杆尺寸8英寸(20.32厘米)";
    } elseif (($footLength >= 122.2 && $footLength < 133.7)) {
        return "矫正鞋号4，连杆尺寸10英寸(25.4厘米)";
    } elseif (($footLength >= 133.7 && $footLength < 143.7)) {
        return "矫正鞋号5，连杆尺寸10英寸(25.4厘米)";
    } elseif (($footLength >= 143.7 && $footLength < 153.7)) {
        return "矫正鞋号6，连杆尺寸10英寸(25.4厘米)";
    } elseif (($footLength >= 153.7 && $footLength < 163.6)) {
        return "矫正鞋号7，连杆尺寸12英寸(30.48厘米)";
    } elseif (($footLength >= 163.6 && $footLength < 173.6)) {
        return "矫正鞋号8，连杆尺寸12英寸(30.48厘米)";
    } elseif (($footLength >= 173.6 && $footLength < 183.6)) {
        return "矫正鞋号9，连杆尺寸12英寸(30.48厘米)";
    } else {
        return "无法定位";
    }

}


/**
 * 预约到店提醒
 * @param $data
 * @return bool
 */
function bookingShopNotify($data) {

    //获得access_token
    $accessToken=access_token();

//    $openidArray = array("otBeowu8bYi2HBRTMBWSIWzzkkbo","otBeowlAfkwtcoHunTHTDVQucZ_E","otBeowv0VZQORekZps57qRBc5d_0","otBeowqZt1N7mSXkLOk4y0ejgVvY","otBeowhbac8rUznUs_ijq2gBKdUM","otBeowka3Gu-RmDy_Fo5rlFCRdrs");

    $employeeList = D("Employee")->alias("e")
        ->join("left join __CUSTOMER__ c on c.customer_id = e.employee_id")
        ->field("e.*, c.openid")
        ->select();
    $openidArray = array();
    foreach ($employeeList as $singleEmployee) {
        $job = explode(',', $singleEmployee["job"]);
        if ($job[0] == "3" || $job[0] == "100") {//亦庄客服
            array_push($openidArray, $singleEmployee["openid"]);
        }
    }
    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"sY0YcYbWI6PX6xYxG_6wfe6ZkiFa9obm_5AnLEj3yvU",
            'data'=>array(
                'first'=>array(
                    'value'=>$data["title"]),
                'keyword1'=>array(
                    'value'=>$data["orderNumber"]),
                'keyword2'=>array(
                    'value'=>$data["serviceName"]),
                'keyword3'=>array(
                    'value'=>1),
                'keyword4'=>array(
                    'value'=>$data["price"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * @param $data
 * @return bool
 */
function wechatNotifyDoctor($data) {

    //获得access_token
    $accessToken=access_token();

    //模板消息
    $template=array(
        'touser'=>$data["openid"],
        'template_id'=>"r0QjIGCKd7f4SF6ywoWD21C3LqdRkEcYDI6a-GSYYTI",
        //'url'=>$data["url"],
        'data'=>array(
            'first'=>array(
                'value'=>$data["title"]),
            'keyword1'=>array(
                'value'=>$data["orderNumber"]),
            'keyword2'=>array(
                'value'=>$data["serviceName"]),
            'keyword3'=>array(
                'value'=>$data["count"]),
            'keyword4'=>array(
                'value'=>$data["price"]),
            'remark'=>array(
                'value'=>$data["remark"])
        )
    );

    $jsonTemplate=json_encode($template);

    $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

    $res=httpRequest($url, urldecode($jsonTemplate));

    return $res["errcode"]==0;

}

/**
 * 收到留言通知提醒  作废
 * @param $data
 * @return bool
 */
function messageboxReceiveNotify($data) {//作废

    //获得access_token
    $accessToken=access_token();

//    $openidArray = array($data["openid"]);
    $openidArray = array("otBeowu8bYi2HBRTMBWSIWzzkkbo","otBeowlAfkwtcoHunTHTDVQucZ_E","otBeowv0VZQORekZps57qRBc5d_0");
    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"iupboVXSm3hoXixuZjVXW7u0EoHc6-ktB_bWiSBJqk01",
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}

/**
 * 留言通知提醒
 * @param $data
 * @return bool
 */
function messageboxNotify($data) {

    //获得access_token
    $accessToken=access_token();

    $openidArray = array($data["openid"]);
    foreach ($openidArray as $openid) {

        //模板消息
        $template=array(
            'touser'=>$openid,
            'template_id'=>"iupboVXSm3hoXixuZjVXW7u0EoHc6-ktB_bWiSBJqk0",
            'url'=>$data["url"],
            'data'=>array(
                'first'=>array(
                    'value'=>$data["first"]),
                'keyword1'=>array(
                    'value'=>$data["keyword1"]),
                'keyword2'=>array(
                    'value'=>$data["keyword2"]),
                'keyword3'=>array(
                    'value'=>$data["keyword3"]),
                'remark'=>array(
                    'value'=>$data["remark"])
            )
        );

        $jsonTemplate=json_encode($template);

        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$accessToken;

        $res=httpRequest($url, urldecode($jsonTemplate));

    }

    return true;

}


function get_millisecond()
{
    list($usec, $sec) = explode(" ", microtime());

    $msec = str_pad(round($usec*1000),3,'0',STR_PAD_LEFT);

    return $msec;
}

function get_total_millisecond()
{
    $time = explode (" ", microtime () );
    $time = $time [1] . ($time [0] * 1000);
    $time2 = explode ( ".", $time );
    $time = $time2 [0];
    return $time;
}

function rand_num($total,$div){

    $area = 10; //各份数间允许的最大差值

    $average = round($total / $div);
    $sum = 0;
    $result = array_fill( 1, $div, 0 );

    for( $i = 1; $i < $div; $i++ ){
        //根据已产生的随机数情况，调整新随机数范围，以保证各份间差值在指定范围内
        if( $sum > 0 ){
            $max = 0;
            $min = 0 - round( $area / 2 );
        }elseif( $sum < 0 ){
            $min = 0;
            $max = round( $area / 2 );
        }else{
            $max = round( $area / 2 );
            $min = 0 - round( $area / 2 );
        }

        if($average + $max > 999) {
            $max = 999;
        }

        if($average + $min < 0) {
            $min = $average;
        }

        //产生各份的份额
        $random = rand( $min, $max );
        $sum += $random;
        $result[$i] = $average + $random;
    }

    //最后一份的份额由前面的结果决定，以保证各份的总和为指定值
    $result[$div] = $total - array_sum($result);

    return array_values($result);
}

function getTimeCode() {
    return date('His').get_millisecond();
}

function calculateDayGap($from, $to) {
    $day = ceil(($to-$from)/60/60/24);
    return $day;
}

function calculateDayGapByTimeStr($from, $to) {
    $day = ceil((strtotime($to)-strtotime($from))/60/60/24);
    return $day;
}

function curlPost($url,$post_data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // post数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // post的变量
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    $output = curl_exec($ch);
    curl_close($ch);
    //返回获得的数据
    return $output;
}

function check_access($customerId, $jobId, $jobLevel = null, $hasAgent = null)
{
    if($hasAgent == 1){
        $map["agent_user_id"] = $customerId;
        $agent = D('Agent')
            ->where($map)
            ->select();
        return $agent;
    }
    $employee = D("Employee")->queryById($customerId);
    $job = explode(',',$employee["job"]);
    if($jobLevel != null){
        if($job[$jobId] >= $jobLevel){
            return true;
        }else{
            return false;
        }
    }
    if($job[$jobId] > 0){
        return true;
    }else{
        return false;
    }
}